#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdlib.h>

int main()
{
    key_t key = ftok(".", 123);
    printf("我是2号: key = %d\n", key);

    int shmid = shmget(key, 1024, 0);
    if(shmid == -1)
    {
        perror("shmget ");
        exit(1);
    }
    else
    {
        printf("成功, shmid = %d\n", shmid);
        sleep(10);
    }
    
    char* shmaddr = (char*)shmat(shmid,NULL,0);
    if(shmaddr == NULL)
    {
        perror("shmat:");
        exit(3);
    }
    printf("挂接成功\n");
    sleep(10);

    //使用
    while(1)
    {
        printf("%s\n",shmaddr);
        sleep(1);
        if(shmaddr[0] == 'q') break;
    }

    int n = shmdt(shmaddr);
    printf("去关联成功\n");
    sleep(10);

    // printf("15秒后删除共享内存 %d\n", shmid);
    // sleep(15);
    // shmctl(shmid, IPC_RMID, NULL);
    // printf("已删除\n");
    return 0;
}